package one.stand.service.sys;

import one.stand.mapper.CustomerLabelMapperExt;
import one.stand.mapper.UserContentMapperExt;
import one.stand.model.UserContent;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Service
public class UserContentServiceImpl implements UserContentService {

    @Autowired
    private UserContentMapperExt userContentMapperExt;
    @Autowired
    private CustomerLabelMapperExt customerLabelMapperExt;

    @Override
    @Transactional
    public void add(int contentType, int contentId, String labels, int userType) {
        Integer[] lableIds = null;
        if (StringUtils.isNoneBlank(labels)) {
            String[] lableIdStrs = (labels.split(","));
            lableIds = new Integer[lableIdStrs.length];
            int i = 0;
            for (String labelIdStr : lableIdStrs) {
                lableIds[i++] = Integer.valueOf(labelIdStr);
            }
        }
        if (Objects.isNull(lableIds)) {
            lableIds = new Integer[]{0};
        }
        updateLabel(contentType, contentId, lableIds);

        userContentMapperExt.deleteByContent(contentType, contentId);
        if (StringUtils.isNoneBlank(labels)) {
            userContentMapperExt.insertByLabels(contentType, contentId, SqlUtil.securitySql(labels));
        } else {
            UserContent userContent = new UserContent();
            userContent.setContentType(contentType);
            userContent.setContentId(contentId);
            userContent.setUserType(userType);
            userContent.setUserId(0);
            userContentMapperExt.insertSelective(userContent);
        }
    }

    @Override
    @Transactional
    public void remove(int contentType, int contentId) {
        updateLabel(contentType, contentId, null);
        userContentMapperExt.deleteByContent(contentType, contentId);
    }

    @Override
    @Transactional
    public void updateLabel(int type, Integer typeId, Integer[] labelIds) {
        // delete
        customerLabelMapperExt.deleteByType(type, typeId);

        // add
        if (Objects.nonNull(labelIds) && labelIds.length > 0) {
            customerLabelMapperExt.insertByType(type, typeId, labelIds);
        }
    }

    @Override
    public List<Integer> getList(int type, Integer typeId) {
        return customerLabelMapperExt.selectList(type, typeId);
    }
}
